package common.util;

import common.LiteralConstants;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

/**
 *
 * @author shousuke
 */
public class FacesUtil {

    public static void addErrorMessage(String msg) {
        addErrorMessage(msg, msg);
    }

    public static void addErrorMessage(String msgSum, String msgDtl) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msgSum, msgDtl);
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);
    }

    public static void addExceptionMessage(Exception ex, String defaultMsg) {
        String msg = ex.getLocalizedMessage();
        if (msg != null && msg.length() > 0) {
            addErrorMessage(msg);
        } else {
            addErrorMessage(defaultMsg);
        }
    }

    public static void addSuccessMessage(String msg) {
        addSuccessMessage(msg, msg);
    }

    public static void addSuccessMessage(String msgSum, String msgDtl) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msgSum, msgDtl);
        FacesContext.getCurrentInstance().addMessage("successInfo", facesMsg);
    }

    public static String getRequestParameter(String name) {
        String reqParamVal = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(name);
        if (reqParamVal != null && reqParamVal.equals(LiteralConstants.EMPTY_STRING)) {
            return null;
        } else {
            return reqParamVal;
        }
    }

    public static void setRequestParameter(String key, String value) {
        FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().put(key, value);
    }

    public static Object getApplicationMapValue(String key) {
        return FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get(key);
    }

    public static void setApplicationMapValue(String key, Object value) {
        FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().put(key, value);
    }

    public static Object getSessionMapValue(String key) {
        return FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(key);
    }

    public static void setSessionMapValue(String key, Object value) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(key, value);
    }
}
